<?php


namespace app\manage\controller;

use think\Log;

class Product extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        $name = input('name','');
        $status = input('status','');

        $map = [];
        if($name != ''){
            $map['name'] = ['like','%'.$name.'%'];
        }

        if($status != 0){
            $map['status'] = $status;
        }

        $infos = model('Product')->getInfosByMap($map, '', false);


        return $this->fetch('',[
            'infos' => $infos,
            'name' => $name,
            'status' => $status,
        ]);
    }
    

    public function edit()
    {
        $id = input('id');
        if(!$id) return self::showReturnCode(1002,'id 错误');
        $user = model('Product')->getInfoByMap(['id'=>$id]);
        return self::showJsonReturnCodeData('1001',$user,'');
    }

    public function save()
    {
        if(request()->isAjax()){
            try{

                $id = input('post.id');
                $save_data = input('post.');

                if(isset($id) && $id){
                    $save_data['id'] = $id;
                }else{
                    $save_data['admin_id'] = $this->uid;
                    unset($save_data['id']);
                }
                $result = $this->editData(false,'','Product',$save_data);
                if($result['code'] == 1001){
                    if(isset($id) && $id){
                        $result['msg'] = '修改产品成功';
                        $this->RecordSystemLog($this->uid,$this->behavior,'修改产品【'.$save_data['name'].'】成功');
                    }else{
                        $result['msg'] = '添加产品成功';
                        $this->RecordSystemLog($this->uid,$this->behavior,'添加产品【'.$save_data['name'].'】成功');
                    }
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    public function status()
    {
        if($this->request->isAjax()){
            $id = input('post.id');
            $res = model('Product')->save(['status'=>input('post.status')],['id'=>$id]);
            if($res){
                $this->RecordSystemLog($this->uid,$this->behavior,'状态操作成功,操作ID: '.$id);
                return $this->showReturnCode(1001);
            }else{
                return $this->showReturnCode(1009,'操作失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }
}